<?php
namespace qiye\controllers;

use common\core\Controller;
use common\helps\Curl;

class SignatureController extends Controller
{
    /*
     * 签名生成规则
     *
     * 签名的参数有四个: noncestr（随机字符串）, jsapi_ticket, timestamp（时间戳）, url（当前网页的URL，不包含#及其后面部分）
     *
     * 此方法为yii框架方法，其他php框架大同小异
     *
     * */
    public $redis;
    public $curl;
    public function init()
    {
        $this->redis = \Yii::$app->redis;
        $this->curl = new Curl();
    }

    //生成签名
    public function actionIndex()
    {
    	$corpId = 'wwd*************';
        $jsapi_ticket = $this->getJsApi($corpId); // 获取 jsapi_ticket
        $noncestr = $this->getStr(); // 随机字符串
        $url = Yii::$app->request->getHostInfo().Yii::$app->request->url; // url
        $timestamp = time();
        $string = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
        $signature = sha1($string); //通过 php sha1(),h获得签名，此处签名可以通过签名工具校验，网址：http://work.weixin.qq.com/api/jsapisign

    	$this->ajaxReturn([
            'status'=>0,
            'appid'=>$corpId,
            'noncestr'=>$noncestr,
            'timestamp'=>$timestamp,
            'signature'=>$signature
        ]);

    }

    //获取 jsapi_ticket
    public function getJsApi($cropid){
        //判断是否已经缓存jsapi_ticket，此处为redis，可用session或其他方式
        if(!$this->redis->get(":jsapi_ticket")){
            $access_token = $this->getAiAccessToken($cropid);
            $jsapi_ticket_url = 'https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token='.$access_token;
            $result = $this->curl->request($jsapi_ticket_url,[],'get');
            $result = json_decode($result);
            $this->redis->set(':jsapi_ticket',$result->ticket);
            $this->redis->expire(':jsapi_ticket',7000);
        }

        return $this->redis->get(":jsapi_ticket");
    }

    //获取aiaccess_token
    public function getAiAccessToken($cropid){
        //判断是否已经缓存jsapi_ticket，此处为redis，可用session或其他方式
        if(!$this->redis->get(':access_token')){
            $access_token_url= 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$cropid.'&corpsecret='.env('SUITE_SECRET_AI');
            $request = $this->curl->request($access_token_url,[],'get');
            $request = json_decode($request);
            $this->redis->set(':ai_access_token',$request->access_token);
            $this->redis->expire(':ai_access_token',7000);
        }

        return $this->redis->get(":ai_access_token");
    }

    //生成随机字符串
    public function getStr(){
        $str="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
        str_shuffle($str);
        return substr(str_shuffle($str),26,10);
    }

   
}